from datetime import datetime
from typing import Optional,List
from uuid import UUID, uuid4

from bisheng.database.base import session_getter
from bisheng.database.models.base import SQLModelSerializable
from sqlalchemy import Column, DateTime, String, Text, text
from sqlmodel import Field, select


class MaintenanceRuleBase(SQLModelSerializable):
    id: UUID = Field(nullable=False, primary_key=True, description='唯一ID')
    equipment_id: str = Field(sa_column=Column(String(length=64), default=''), description='故障设备编号')
    equipment_name: str = Field(sa_column=Column(String(length=255), default=''), description='故障设备名称')
    equipment_unit: str = Field(sa_column=Column(String(length=64), default=''),description='设备单元')
    maintenance_kind: str = Field(sa_column=Column(String(length=64),default=''),description='检修类别')
    maintenance_program: str = Field(sa_column=Column(String(length=64),default=''),description='检修项目')
    maintenance_standard: str = Field(sa_column=Column(Text),default="",description='检修标准')
    maintenance_cycle_unit: str = Field(sa_column=Column(String(length=64),default=''),description='检修周期单位')
    maintenance_cycle_threshold: str = Field(sa_column=Column(String(length=64), default=''), description='检修周期阈值')
    publish_time: Optional[datetime] = Field(sa_column=Column(DateTime),description='发布日期')
    strategyName: str = Field(sa_column=Column(String(length=255),default=''),description='策略名称')
    strategyNumber: str = Field(sa_column=Column(String(length=255),default=''),description='策略编号')
    strategyDescription: str=Field(sa_column=Column(Text),default="",description='策略描述')


    create_time: Optional[datetime] = Field(
        sa_column=Column(DateTime, nullable=False, server_default=text('CURRENT_TIMESTAMP')))
    update_time: Optional[datetime] = Field(
        sa_column=Column(DateTime,
                         nullable=False,
                         index=True,
                         server_default=text('CURRENT_TIMESTAMP'),
                         onupdate=text('CURRENT_TIMESTAMP')))


class MaintenanceRule(MaintenanceRuleBase, table=True):
    id: UUID = Field(default_factory=uuid4, primary_key=True, unique=True)

class MaintenanceRuleDao(MaintenanceRule):
    @classmethod
    def get_by_equipment_id(cls, equipment_id: str) -> List[MaintenanceRule]:
        with session_getter() as session:
            statement = select(MaintenanceRule).where(MaintenanceRule.equipment_id == equipment_id)
            return session.exec(statement).all()

    @classmethod
    def create_maintenance_rule(cls,maintenance_rules: List[MaintenanceRule]):
        with session_getter() as session:
            session.add_all(maintenance_rules)
            session.commit()

    @classmethod
    def delete_all(cls):
        with session_getter() as session:
            session.query(MaintenanceRule).delete()
            session.commit()
    

